<template>
    <div
        class="fishing-trend-root"
        :class="{ 'has-custom-range': selectedTime === 'custom' }"
        style="width: 100%; height: 100%; position: relative;"
    >
        <div ref="chartContainer" style="width: 100%; height: 100%;"></div>
        <div class="time-selector">
            <label 
                v-for="option in timeOptions" 
                :key="option.value"
                class="radio-label"
                :class="{ active: selectedTime === option.value }"
            >
                <input 
                    type="radio" 
                    :value="option.value" 
                    v-model="selectedTime"
                    @change="handleTimeChange"
                    class="radio-input"
                />
                <span class="radio-text">{{ option.label }}</span>
            </label>
        </div>
        <div
            v-if="selectedTime === 'custom'"
            class="custom-date-range"
        >
            <input
                type="date"
                v-model="customDateRange.startDate"
                @change="onCustomDateChange"
                class="date-input"
                placeholder="开始日期"
            />
            <span class="date-separator">至</span>
            <input
                type="date"
                v-model="customDateRange.endDate"
                @change="onCustomDateChange"
                class="date-input"
                placeholder="结束日期"
            />
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts'
import { createChartOption } from './option.js'
import axios from 'axios'

export default {
    props: {
        Data: {
            type: Object,
            required: false
        }
    },
    data() { 
        return {
            chartInstance2: null,
            resizeObserver: null,
            optionsData: {},
            loading: false,
            error: null,
            selectedTime: 'week', // week, month, year
            timeOptions: [
                { label: '近一周', value: 'week' },
                { label: '近一月', value: 'month' },
                { label: '近一年', value: 'year' },
                { label: '自定义', value: 'custom' }
            ],
            customDateRange: {
                startDate: '',
                endDate: ''
            },
            customOptionsData: {
                timeLabels: [],
                seriesData: []
            },
            fishingGrounds: [
                '印度洋公海渔场',
                '北太平洋公海渔场',
                '东南太平洋公海渔场',
                '西南大西洋公海渔场'
            ],
            colors: [
                'rgba(79,191,227,1)',
                'rgba(249,170,114,1)',
                'rgba(179,229,251,1)',
                'rgba(250,210,95,1)'
            ]
        };
    },
    watch: {
        Data: {
            handler(newData) {
                if (newData && Object.keys(newData).length > 0) {
                    this.updateData(newData);
                }
            },
            deep: true,
            immediate: true
        }
    },
    mounted() {
        this.initChart();
        this.fetchFishingTrendData();
    },
    methods: {
        initChart() {
            if (this.$refs.chartContainer) {
                this.chartInstance2 = echarts.init(this.$refs.chartContainer, this.$echartsConfig.theme);
                this.resizeObserver = new ResizeObserver(() => {
                    this.chartInstance2 && this.chartInstance2.resize();
                });
                this.resizeObserver.observe(this.$refs.chartContainer);
            }
        },
        updateChart() {
            if (!this.chartInstance2) return;
            
            let sourceData = null;

            if (this.selectedTime === 'custom') {
                sourceData = this.customOptionsData;
            } else if (this.Data && Object.keys(this.Data).length > 0) {
                sourceData = this.Data;
            } else {
                sourceData = this.generateMockData(this.selectedTime);
            }

            if (
                !sourceData ||
                !Array.isArray(sourceData.timeLabels) ||
                sourceData.timeLabels.length === 0 ||
                !Array.isArray(sourceData.seriesData) ||
                sourceData.seriesData.length === 0
            ) {
                this.chartInstance2.clear();
                return;
            }

            this.optionsData = sourceData;
            
            const option = createChartOption(
                this.optionsData.timeLabels,
                this.optionsData.seriesData,
                this.fishingGrounds,
                this.colors
            );
            this.chartInstance2.setOption(option, true);
        },
        updateData(newData) {
            this.optionsData = newData;
            this.updateChart();
        },
        handleTimeChange() {
            if (this.selectedTime === 'custom') {
                if (this.customDateRange.startDate && this.customDateRange.endDate) {
                    this.generateCustomTrendData();
                } else if (this.chartInstance2) {
                    this.customOptionsData = { timeLabels: [], seriesData: [] };
                    this.chartInstance2.clear();
                }
            } else {
                this.updateChart();
            }
        },
        onCustomDateChange() {
            if (this.selectedTime !== 'custom') return;
            if (this.customDateRange.startDate && this.customDateRange.endDate) {
                this.generateCustomTrendData();
            }
        },
        async fetchFishingTrendData() {
            try {
                this.loading = true;
                this.error = null;
                
                const response = await axios.get('/getdata/fishing-trend/');
                
                if (response.data.code === 200) {
                    // 如果没有传入props数据，则使用API数据
                    if (!this.Data || Object.keys(this.Data).length === 0) {
                        this.optionsData = response.data.data;
                        this.updateChart();
                    }
                } else {
                    this.error = response.data.message || '获取数据失败';
                    console.error('获取渔场捕捞量趋势数据失败:', this.error);
                }
            } catch (error) {
                this.error = error.message || '获取数据失败';
                console.error('获取渔场捕捞量趋势数据出错:', error);
                
                // 如果API请求失败，使用默认mock数据
                if (!this.Data || Object.keys(this.Data).length === 0) {
                    this.optionsData = this.generateMockData(this.selectedTime);
                    this.updateChart();
                }
            } finally {
                this.loading = false;
            }
        },
        generateCustomTrendData() {
            const { startDate, endDate } = this.customDateRange;
            const start = new Date(startDate);
            const end = new Date(endDate);

            if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {
                return;
            }
            if (start > end) {
                return;
            }

            const dayMilliseconds = 1000 * 60 * 60 * 24;
            const daysDiff = Math.floor((end - start) / dayMilliseconds) + 1;

            if (daysDiff <= 0) {
                return;
            }

            let timeLabels = [];

            if (daysDiff <= 30) {
                for (let i = 0; i < daysDiff; i++) {
                    const date = new Date(start);
                    date.setDate(start.getDate() + i);
                    timeLabels.push(this.formatDate(date));
                }
            } else if (daysDiff <= 365) {
                const weeks = Math.ceil(daysDiff / 7);
                for (let i = 0; i < weeks; i++) {
                    const date = new Date(start);
                    date.setDate(start.getDate() + i * 7);
                    timeLabels.push(this.formatDate(date));
                }
            } else {
                const months = Math.ceil(daysDiff / 30);
                for (let i = 0; i < months; i++) {
                    const date = new Date(start);
                    date.setMonth(start.getMonth() + i);
                    timeLabels.push(this.formatMonth(date));
                }
            }

            const baseValues = [1500, 2800, 3500, 2100];

            const seriesData = this.fishingGrounds.map((ground, index) => {
                const data = [];

                if (daysDiff <= 30) {
                    for (let i = 0; i < timeLabels.length; i++) {
                        data.push(Math.floor(Math.random() * 600 + baseValues[index]));
                    }
                } else if (daysDiff <= 365) {
                    for (let i = 0; i < timeLabels.length; i++) {
                        data.push(Math.floor(Math.random() * 3200 + baseValues[index] * 2));
                    }
                } else {
                    for (let i = 0; i < timeLabels.length; i++) {
                        data.push(Math.floor(Math.random() * 6000 + baseValues[index] * 9));
                    }
                }

                return {
                    name: ground,
                    type: 'line',
                    smooth: true,
                    data: data,
                    itemStyle: {
                        color: this.colors[index]
                    },
                    lineStyle: {
                        color: this.colors[index],
                        width: 2
                    },
                    areaStyle: {
                        color: this.colors[index],
                        opacity: 0.1
                    }
                };
            });

            this.customOptionsData = {
                timeLabels,
                seriesData
            };

            this.updateChart();
        },
        generateMockData(timeType) {
            let timeLabels = [];
            let dataPoints = 0;
            let baseDate = new Date();
            
            // 根据时间类型生成时间标签和数据点
            if (timeType === 'week') {
                dataPoints = 7;
                for (let i = 6; i >= 0; i--) {
                    const date = new Date(baseDate);
                    date.setDate(date.getDate() - i);
                    timeLabels.push(this.formatDate(date));
                }
            } else if (timeType === 'month') {
                dataPoints = 30;
                for (let i = 29; i >= 0; i--) {
                    const date = new Date(baseDate);
                    date.setDate(date.getDate() - i);
                    timeLabels.push(this.formatDate(date));
                }
            } else if (timeType === 'year') {
                dataPoints = 12;
                for (let i = 11; i >= 0; i--) {
                    const date = new Date(baseDate);
                    date.setMonth(date.getMonth() - i);
                    timeLabels.push(this.formatMonth(date));
                }
            }
            
            // 生成四个渔场的数据
            const seriesData = this.fishingGrounds.map((ground, index) => {
                const baseValue = [1500, 2800, 3500, 2100][index]; // 基础值
                const data = [];
                
                for (let i = 0; i < dataPoints; i++) {
                    // 添加随机波动，使数据更真实
                    const variation = (Math.random() - 0.5) * 0.3; // -15% 到 +15% 的波动
                    let value = Math.max(0, Math.round(baseValue * (1 + variation)));
                    
                    // 如果是年度数据，数值更大
                    if (timeType === 'year') {
                        value = value * (28 + Math.random() * 5); // 一个月的数据量
                    }
                    data.push(value);
                }
                
                return {
                    name: ground,
                    type: 'line',
                    smooth: true,
                    data: data,
                    itemStyle: {
                        color: this.colors[index]
                    },
                    lineStyle: {
                        color: this.colors[index],
                        width: 2
                    },
                    areaStyle: {
                        color: this.colors[index],
                        opacity: 0.1
                    }
                };
            });
            
            return {
                timeLabels,
                seriesData
            };
        },
        formatDate(date) {
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${month}-${day}`;
        },
        formatMonth(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            return `${year}-${month}`;
        }
    },
    beforeDestroy() {
        if (this.chartInstance2) {
            this.chartInstance2.dispose();
        }
        if (this.resizeObserver && this.$refs.chartContainer) {
            this.resizeObserver.unobserve(this.$refs.chartContainer);
            this.resizeObserver.disconnect();
        }
    }
};
</script>

<style scoped lang="less">
.fishing-trend-root {
    width: 100%;
    height: 100%;
    position: relative;
}

.time-selector {
    position: absolute;
    top: 5px;
    right: 5px;
    z-index: 10;
    display: flex;
    gap: 8px;
    padding: 4px;
    background: rgba(0, 0, 0, 0.4);
    border-radius: 4px;
    pointer-events: auto;

    .radio-label {
        display: flex;
        align-items: center;
        cursor: pointer;
        padding: 3px 6px;
        border-radius: 3px;
        transition: all 0.3s;
        color: rgba(255, 255, 255, 0.7);
        font-size: 11px;
        white-space: nowrap;

        &.active {
            background: rgba(79, 191, 227, 0.6);
            color: #fff;
        }

        &:hover {
            background: rgba(79, 191, 227, 0.4);
            color: #fff;
        }

        .radio-input {
            display: none;
        }

        .radio-text {
            user-select: none;
        }
    }
}

.custom-date-range {
    position: absolute;
    top: 42px;
    right: 5px;
    z-index: 9;
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 4px 6px;
    background: rgba(0, 0, 0, 0.32);
    border-radius: 4px;
    pointer-events: auto;
}

.date-input {
    padding: 0.3rem 0.6rem;
    background: rgba(12, 30, 60, 0.55);
    border: 1px solid rgba(79, 191, 227, 0.45);
    border-radius: 3px;
    color: #FFFFFF;
    font-size: 10px;
    outline: none;
    transition: all 0.3s ease;
}

.date-input:hover,
.date-input:focus {
    border-color: rgba(79, 191, 227, 0.8);
    background: rgba(12, 30, 60, 0.75);
}

.date-separator {
    color: rgba(255, 255, 255, 0.75);
    font-size: 10px;
    user-select: none;
}

.date-input::-webkit-calendar-picker-indicator {
    filter: invert(1);
    cursor: pointer;
}
</style>

